import os

def splitsql(file,nums,storepath):
    fd=open(file, encoding='utf-8')

    lines = fd.readlines()

    filename = os.path.basename(file).split(".")[0]
    # win默认桌面路径（未修改桌面路径）
    desktop=os.path.join(os.path.expanduser("~"), 'Desktop')
    if storepath == "":
        print("storepath is '',set storepath is defautl window desktop")
        storepath = desktop
    firstLine = lines[0];
    # print(firstLine)
    # print(len(lines))

    #干掉第一行
    lines = lines[1:]
    # print(lines)


    for i in range(int(len(lines)/nums+1)):
        j = i + 1
        # tempname = "lang2\\" + filename + str(j) + '.sql'
        tempname = filename + str(j) + '.sql'
        # print(i)
        temp = lines[nums*i:nums*(i+1)]


        if len(temp) > 0:
            temp[-1] = temp[-1].strip()[0:-1] + ';'
            # print(temp)


            file_write_obj=open(os.path.join(storepath,tempname), 'w', encoding="utf-8")  # 新文件
            file_write_obj.write(firstLine)  # 逐行写入
            for var in temp:
                # print(var)
                file_write_obj.write(var)  # 逐行写入
                # file_write_obj.write('\n')
            file_write_obj.close()


        # print(len(temp))
        # break





if __name__ == '__main__':
    #原sql文件
    file ='../数据测试集/批处理sql到多个文件.sql'
    #按几行分割
    nums=2
    #生成的文件路径，为空默认为未修改路径的win桌面
    storepath = '数据结果集'
    splitsql(file,nums,storepath)